﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Domain.ActiveDirectory.Provider;
using Domain.Logging;
using Domain.Provider;
using Ninject;
using Ninject.Activation;

namespace WebUI.Infrastructure
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel kernel;
        private DatabaseProvider _dataRepo;
        private LogService _service;

        public NinjectControllerFactory()
        {
            kernel = new StandardKernel();

            ApplyBindings();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null ? null : (IController)kernel.Get(controllerType);
        }

        public void ApplyBindings()
        
        {
            kernel.Bind<LogService>().ToMethod(getLogger);
            kernel.Bind<IActiveDirectoryDataProvider>().To<ActiveDirectoryDataProvider>().InSingletonScope();
            kernel.Bind<IDataProvider<Domain.ActiveDirectory.Model.User>>().To<NMCDataProvider>().InSingletonScope();
            kernel.Bind<IDataProvider<Domain.Context.NMCTerritory>>().ToMethod(GetProvider);
            kernel.Bind<IDataProvider<Domain.Context.AccountType>>().ToMethod(GetProvider);
            kernel.Bind<IDataProvider<Domain.Context.Store>>().ToMethod(GetProvider);
            kernel.Bind<IActiveDirectoryDataProvider>().To<ActiveDirectoryDataProvider>().InSingletonScope();
        }

        public LogService getLogger(IContext context)
        {
            if (_service == null)
                _service = new FileLogger("Logs");

            return _service;
        }

        public DatabaseProvider GetProvider(IContext context)
        {
            if (_dataRepo == null)
                _dataRepo = new DatabaseProvider();

            return _dataRepo;
        }
    }
}